<?php
/**
 * Created by PhpStorm.
 * User: 沁塵
 * Date: 2019/4/20
 * Time: 19:57
 */

namespace app\api\controller\v1;

use app\api\model\LinUser;
use app\api\model\LiveChild;
use app\api\model\LiveCommander;
use app\api\model\LiveConsume;
use app\api\model\LiveContact;
use app\api\model\LiveGenbo;
use app\api\model\LiveGeneral;
use app\api\model\LiveMajor;
use app\api\model\LiveMother;
use app\api\model\LiveProduct;
use app\api\model\LiveProductTask;
use app\api\model\LiveProductTaskChild;
use app\api\model\LiveProductText;
use app\api\model\LiveSession;
use app\api\model\LiveVoice;
use app\api\model\Service;
use app\api\model\TbAudio;
use app\api\model\TbLog;
use app\api\service\LiveService;
use app\api\service\token\LoginToken;
use think\Db;
use think\Exception;
use think\Request;
use think\facade\Cache;

require_once '../vendor/PHPExcel/Classes/PHPExcel/IOFactory.php';
require_once '../vendor/PHPExcel/Classes/PHPExcel/Reader/Excel5.php';
use PHPExcel;
use PHPExcel_IOFactory;

class Live
{


    // 根据名字获取主播模型
    public function getVoiceByName(Request $request)
    {
        $name = $request->get()['name'];

        $voice = LiveVoice::where('guang_model',$name)->find();

        return  writeJson(200, $voice, 'voice');
    }

    public function getHuoVoice()
    {
        $voice = LiveVoice::field("id,guang_model,huo_voice")->whereNotNull('huo_voice')->select()->toArray();
        return  writeJson(200, $voice, 'voice');

    }


    public function getVoiceByVoice(Request $request)
    {
        $name = $request->get()['voice'];

        $voice = LiveVoice::where('voice',$name)->find();

        return  writeJson(200, $voice, 'voice');
    }

    public function getVoiceByHuoVoice(Request $request)
    {
        $name = $request->get()['voice'];

        $voice = LiveVoice::where('huo_voice',$name)->find();

        return  writeJson(200, $voice, 'voice');
    }
    public function getVoiceByBobaVoice(Request $request)
    {
        $name = $request->get()['voice'];

        $voice = LiveVoice::where('boba_voice',$name)->find();

        return  writeJson(200, $voice, 'voice');
    }

    public function randomHuoVoice()
    {
        $voice = LiveVoice::whereNotNull('boba_voice')->orderRand()->find();
        return  writeJson(200, $voice, 'voice');
    }


    public function addProduct(Request $request)
    {
        $params = $request->post();

        $pname = $params['pname'];
        $exists = (new LiveProduct())->where('pname',$params['pname'])->find();
        if($exists){
            return  writeJson(400, null, '商品已存在');
        }

        $res = (new LiveProduct)->create($params);

        return writeJson(200, $res, '新增商品');
    }

    public function getProduct(Request $request)
    {

        $params = $request->get();
        $uid = LoginToken::getInstance()->getCurrentUid();
        $query = LiveProduct::field("a.*,b.username")->alias('a')->join('lin_user b', 'a.uid=b.id');
        if(!empty($params["pname"])){
            $query = $query->where('pname','like','%'.$params["pname"].'%');
        }
        if($uid != 1){
            $query = $query->where('uid',$uid);
        }

       $result = $query->order("id desc")->paginate(20);
        return writeJson(200, $result, '商品列表');
    }

    public function editProduct(Request $request)
    {
        $params = $request->post();
        $id = $params['id'];
        $product = LiveProduct::where('id',$id)->find();
        $product->zb_voice = $params['zb_voice'];
        $product->fb_voice = $params['fb_voice'];
        $product->pname = $params['pname'];
        $product->uid = $params['uid'];
        $product->save();

        return  writeJson(200, $product, '修改商品');
    }


    public function delProduct(Request $request)
    {

        $params = $request->post();
        $id = $params['id'];
        $p = LiveProduct::where('id',$id)->find();
        $p->delete();


        return  writeJson(200, $p, '删');
    }





    public function getTextByProduct(Request $request)
    {
        $params = $request->get();


        $texts = LiveProductText::where('pid',$params['pid'])->paginate(200);

        return writeJson(200, $texts, '话术列表');

    }

   public function addText(Request $request)
   {
       $params = $request->post();

       $texts = $params['texts'];
       if(!is_array($params['texts'])){
           $texts = json_decode($texts,true);
       }

       $num = 0;
       foreach ($texts as $item){
           $exists = LiveProductText::where('text',$item['text'])->where('pid',$item['pid'])->findOrEmpty();
           if($exists->isEmpty()){
               LiveProductText::create($item);
               $num = $num+1;
           }
       }


       return writeJson(200, $num, '新增话术');

   }


   public function editText(Request $request)
   {
       $params = $request->post();
       $id = $params['id'];
       $text = LiveProductText::where('id',$id)->find();
       $text->text = $params['text'];
       $text->save();

       return  writeJson(200, $text, '修改话术');
   }

    public function delText(Request $request)
    {
        $params = $request->post();
        $ids = $params['ids'];
        $res = LiveProductText::whereIn('id',$ids)->delete();

        return  writeJson(200, $res, '删除话术');
    }

    public function addTask(Request $request)
    {
        $params = $request->post();

        $task = new LiveProductTask();
        $info = $task->where("tname", $params["tname"])->count();
        if ($info > 0) {
            return writeJson(200, false, '任务已存在');
        } else {
//            $text = LiveProductText::where("pid", $params["pid"])->where("type", "主播")->count();
//            if ($text < 600) {
//                return writeJson(200, "", '主播话术不足600');
//            }
            //检查话术表是否有状态不为3的
            $product = LiveProduct::where("id", $params["pid"])->findOrEmpty();
            if ($product["status"] != null) { //做个兼容
                $total = LiveProductText::where("pid", $params["pid"])->count();
                if ($total == 0) {
                    return writeJson(200, false, '改产品还未添加话术');
                }
                $count = LiveProductText::where("pid", $params["pid"])->where("status", "<>", 3)->count();
                if ($total > 0 && $count > 0) {
                    return writeJson(200, false, '直播话术准备中');
                } else if ($total > 0 && $count == 0) {
                    if ($product["status"] == 1) {
                        $product->status = 3;
                        $product->save();
                    }
                }
            }

            $product = LiveProduct::where("id", $params["pid"])->findOrEmpty();
            $params["zb_voice"] = $product["zb_voice"];
            $params["fb_voice"] = $product["fb_voice"];
            if ($product["status"] != null) {
                $params["status"] = 21;
            } else {
                $params["status"] = 11;
            }
            $res = $task->create($params);
        }

        return writeJson(200, $res, '新增任务');
    }
    public function getGeneralText()
    {
        $texts = LiveGeneral::order('RAND()')->limit(4000)->select();
        return writeJson(200, $texts, '成功');
    }
    public function getTask11(Request $request)
    {
        $params = $request->get();
        $status = $params["status"]??11;
        $task = LiveProductTask::where('status',$status)->findOrEmpty();
        if (!$task->isEmpty()) {
            return writeJson(200, $task, '获取待下发任务');
        } else {
            return writeJson(200, [], '暂无待下发任务');
        }
    }

//    检查任务是否跑完
    public function checkTask(Request $request)
    {
        $params = $request->get();
        if (isset($params["id"])) {
            $task = LiveProductTask::where("id", $params["id"])->where("status", 1)->findOrEmpty();
        } else {
            $task = LiveProductTask::where("status", 1)->findOrEmpty();
        }
        if (!$task->isEmpty()) {
            $total_count = LiveProductTaskChild::where("task_id", $task["id"])->count();
            $count = LiveProductTaskChild::where("task_id", $task["id"])->where("status", "<>", 3)->count();
            if ($total_count != 0 && $count == 0) {
                $task->status = 3;
//                如果是优先任务 要移除
                if ($task["is_top"] == 1) {
                    $task->is_top = 0;
                }
                $task->save();

                return writeJson(200, true, "任务{$task['tname']}已完成");
            } else {
                return writeJson(200, true, "任务{$task['tname']}进行中");
            }
        } else {
            return writeJson(200, true, "暂无未完成任务");
        }
    }

    //    检查话术是否裂变完
    public function checkProduct(Request $request)
    {
        $params = $request->get();
        if (isset($params["id"])) {
            $task = LiveProduct::where("id", $params["id"])->where("status", 1)->findOrEmpty();
        } else {
            $task = LiveProduct::where("status", 1)->findOrEmpty();
        }
        if (!$task->isEmpty()) {
            $count = LiveProductText::where("pid", $task["id"])->where("status", "<>", 3)->count();
            if ($count == 0) {
                $task->status = 3;
//                如果是优先任务 要移除
                if ($task["is_top"] == 1) {
                    $task->is_top = 0;
                }
                $task->save();

                return writeJson(200, true, "产品{$task['pname']}已完成");
            } else {
                return writeJson(200, true, "产品{$task['pname']}进行中");
            }
        } else {
            return writeJson(200, true, "暂无未完成任务");
        }
    }


//    查询话术总量
    public function taskTextCount(Request $request)
    {
        $params = $request->get();
        $text_count = LiveProductText::where("pid", $params["pid"])->where("type", $params["type"])->count();
        return writeJson(200, $text_count, '成功');
    }

    public function get4000General(Request $request)
    {
        $params = $request->get();

        $event = new LiveGeneral();
        $text = $event->orderRand()->limit($params["fission_count"])->select()->toArray();
        return writeJson(200, $text, '成功');
    }

    public function getbatchText(Request $request)
    {
        $params = $request->post();
        $limit = $params["limit"];
        $un_ids = json_decode($params["un_ids"], true);
        $pid = $params["pid"];
        $type = $params["type"];

        $texts = LiveProductText::where("pid", $pid)->where("type", $type)
            ->whereNotIn("id", $un_ids)->orderRand()->limit($limit)->select()->toArray();

        return writeJson(200, $texts, '成功');

    }

    public function addTaskChild(Request $request)
    {
        $params = $request->post();
        $child = new LiveProductTaskChild();
        $res = $child->create($params);

        return writeJson(200, $res, '新增');
    }

    public function addTaskChildZb(Request $request)
    {
        $params = $request->post();
        $child = new LiveProductTaskChild();
        $i = 0;

        $data = json_decode($params["data"], true);
        foreach ($data as $da) {
            $add = [
                'task_id' => $params['task_id'],
                'group' => $da['group'],
                'text' => $da['text'],
                'type' => "主播",
                'voice' => $params["voice"]
            ];
            $child->create($add);
            $i++;
        }
        return writeJson(200, $i, '新增');

    }

    public function addTaskChildFb(Request $request)
    {
        $params = $request->get();
        $child = new LiveProductTaskChild();
        $task = LiveProductTask::where("id", $params["id"])->findOrEmpty();
//      主播话术批量插入子表
        $limit = $params["limit"];
        $offset = $params["offset"];
        $i = 0;
        $texts = LiveProductText::where("pid", $params["pid"])->where("type", $params["type"])
            ->limit($offset, $limit)->select()->toArray();

        // 插入到子表
        foreach ($texts as $row) {
            if (!empty($row["text"])) {
                // 假设主表和子表结构相同，提取需要的列
                $data = [
                    'task_id' => $params['id'],
                    'group' => $row['group'],
                    'text' => $row['text'],
                    'type' => $row['type']
                ];
                if ($params["type"] == "主播") {
                    $data["voice"] = $task["zb_voice"];
                } else {
                    $data["voice"] = $task["fb_voice"];
                }

                // 插入到子表
                $child->create($data);
                $i++;
            }
        }


        return writeJson(200, "offset:{$offset},limit:{$limit},i:{$i}", '新增');
    }

    public function getTaskChild()
    {
        $tasks = LiveProductTask::field("id")->where("is_top", 1)->where("status", 1)->select()->toArray();
        $ids = [];
        $info = [];
        if (!empty($tasks)) {
            foreach ($tasks as $ta) {
                $ids[] = $ta["id"];
            }
            $info = LiveProductTaskChild::where("status", 1)
                ->whereIn("task_id",$ids)
                ->where(function ($q){
                    $q->whereNull('deal_time')->whereOr('deal_time','<',date("Y-m-d H:i:s", time()));
                })
                ->order("id desc")->findOrEmpty();
        }

        if (empty($info)) {
            $info = LiveProductTaskChild::where("status", 1)
                ->where(function ($q){
                    $q->whereNull('deal_time')->whereOr('deal_time','<',date("Y-m-d H:i:s", time()));
                })
                ->findOrEmpty();
        }


        if (!$info->isEmpty()) {
            $info->status = 2;
            $info->get_time = date("Y-m-d H:i:s");
            $info->save();
            return writeJson(200, $info, "成功");
        } else {
            return writeJson(200, [], '暂无');
        }
    }

    //    检查任务话术是否加完
    public function checkTaskStatus(Request $request)
    {
        $params = $request->get();

        $task = LiveProductTask::where("tname", $params["tname"])->findOrEmpty();
        if (!$task->isEmpty()) {
            if ($task["status"] == 3) {
                // 总话术量
                $count = LiveProductTaskChild::where("task_id", $task["id"])->where("status", 3)->count();
                $task["count"] = $count;
                return writeJson(200, $task, "成功");
            } else {
                return writeJson(200, "任务未完成", "任务未完成");
            }
        } else {
            return writeJson(200, "无该任务", "无该任务");
        }
    }

    public function getBatchTaskChild(Request $request)
    {
        $params = $request->get();
        if (isset($params["max_id"]) && !empty($params["max_id"])) {
            $info = LiveProductTaskChild::where("task_id", $params["task_id"])->where("id", ">", $params["max_id"])
                ->where("status", 3)->limit($params["offset"], $params["limit"])->select()->toArray();
        } else {
            $info = LiveProductTaskChild::where("task_id", $params["task_id"])->where("status", 3)
                ->limit($params["offset"], $params["limit"])->select()->toArray();
        }

        if (!empty($info)) {
            return writeJson(200, $info, "成功");
        } else {
            return writeJson(200, [], '暂无');
        }
    }

    public function setTaskChild(Request $request)
    {
        $params = $request->post();
        $info = LiveProductTaskChild::where("id", $params["id"])->findOrEmpty();
        if (!$info->isEmpty()) {
            $info->status = $params["status"];

            if (isset($params["url"])) {
                $info->url = $params["url"];
            }
            if (isset($params["reason"])) {
                $info->reason = $params["reason"];
            }
            if (isset($params["identifier"])) {
                $info->identifier = $params["identifier"];
            }
            $info->save();
            return writeJson(200, $info, "成功");
        } else {
            return writeJson(200, [], '暂无');
        }
    }

    public function getTaskList(Request $request)
    {
        $params = $request->get();


        $texts = LiveProductTask::where('pid',$params['pid'])
            ->order('create_time','desc')
            ->paginate(20);

        return writeJson(200, $texts, '任务列表');

    }

    public function getTask(Request $request)
    {
       $task = LiveProductTask::where('status',1)->find();
        if(empty($task)){
            return writeJson(200, null, '暂无数据');
        }

        $product = LiveProduct::where('id',$task['pid'])->find();

        $task->status = 2;
        $task->save();

        $task->zb_voice = $product['zb_voice'];
        $task->fb_voice = $product['fb_voice'];

        $zb_texts = LiveProductText::where('pid',$task['pid'])->where('type','主播')->select();
        $zb_texts = json_encode($zb_texts, 360);

        $fb_texts = LiveProductText::where('pid',$task['pid'])->where('type','副播')->select();
        $fb_texts = json_encode($fb_texts, 360);
        $task->zb_texts = $zb_texts;
        $task->fb_texts = $fb_texts;

        return writeJson(200, $task, '获取待执行任务');

    }

    public function backTask(Request $request)
    {
        $params = $request->post();
        $task = LiveProductTask::where('id',$params["id"])->findOrEmpty();
        $task->status = $params["status"];

        if (isset($params["link"])) {
            $task->link = str_replace("http://f45k840659.zicp.vip:12109", "http://xstar5470.ticp.io", $params["link"]);
        }
        if (isset($params["reason"])) {
            $task->reason = $params["reason"];
        }
        $task->save();
        return writeJson(200,$task,'回填成功');

    }

    public function leaderList()
    {
        $list = LinUser::field("id, username")->where("group_id", 4)->select()->toArray();
        return writeJson(200,$list,'成功');
    }

    public function getLastTask(Request $request)
    {
        $params = $request->get();
        $task = LiveProductTask::field("link")->where("id", "<", $params["id"])->where("pid", $params["pid"])
            ->where("status", 3)
            ->order("id desc")->limit(2)->select()->toArray();
        if (count($task) == 2) {
            return writeJson(200,$task[1],'成功');
        } else {
            return writeJson(200,[],'成功');
        }
    }

    public function voiceSync()
    {
        $url = "http://xstar5470.ticp.io/v1/ai/models";
        $models = file_get_contents($url);
        $models = json_decode($models,true);
        $models = $models['result'];


        $new_models = [];
        foreach ($models as $model){
            $new_models[] = $model;
            if($model == '.' || $model == '..'){
                continue;
            }
            $flag = LiveVoice::where('voice',$model)->find();
            if(!$flag){
                LiveVoice::create([
                    'voice' => $model
                ]);
            }

        }


        // 把不属于线上的声音模型删掉
        LiveVoice::whereNotIn('voice',$new_models)->delete();

        return writeJson(200,1,'成功');
    }


    public function getVoiceAll()
    {
        $uid = LoginToken::getInstance()->getCurrentUid();

        if ($uid == 1) {
            $res = LiveVoice::where('id','>=',1)->with("linuser")->select();
        } else {
            $res = LiveVoice::where('id','>=',1)->with("linuser")->where("uid", $uid)->select();
        }

        return writeJson(200,$res,'成功');
    }


    public function editVoice(Request $request)
    {
        $params = $request->post();

        $res = LiveVoice::where('id',$params['id'])->update([
            "guang_model" => $params['guang_model'],
            "guang_speed" => $params['guang_speed']
        ]);

        return writeJson(200,$res,'成功');
    }

//    重置30分钟前的
    public function resetStatus()
    {
        $list = LiveProductTaskChild::where("status", "<>", 3)
            ->whereNotNull("get_time")
            ->where("update_time", "<", date("Y-m-d H:i:s", time() - 900))
            ->select()->toArray();
        $ids = [];
        if (!empty($list)) {
            foreach ($list as $li) {
                $ids[] = $li["id"];
            }
            $res = LiveProductTaskChild::whereIn("id", $ids)->update(["status"=>1]);
            return writeJson(200,$res,'成功');
        } else {
            return writeJson(200,0,'暂无');
        }
    }

    public function setTopTask(Request $request)
    {
        $params = $request->get();
        $count = LiveProductTask::where("status", "<>", 3)->where("is_top", 1)->count();
        if ($count >= 12) {
            return writeJson(200,"优先任务数量已上限",'成功');
        }
        $task = LiveProductTask::where("id", $params["id"])->findOrEmpty();
        if (!$task->isEmpty()) {
            if ($task["is_top"] == 0) {
                $task->is_top = 1;
            } else {
                $task->is_top = 0;
            }
            $task->save();
        }
        return writeJson(200,true,'成功');
    }

    public function getTopTask()
    {
        $tasks = LiveProductTask::where("is_top", 1)->select()->toArray();
        $ids = [];
        if (!empty($tasks)) {
            foreach ($tasks as $ta) {
                $ids[] = $ta["id"];
            }
        }
        return writeJson(200, $ids, '获取成功');

    }

    public function copyTask(Request $request)
    {
        $params = $request->get();
//        DB::startTrans();
//        try {
            $texts = LiveProductText::field("text,group,type")->where("pid", $params["pid"])->select()->toArray();
            if (empty($texts)) {
                return writeJson(200, false, '该商品还未导入话术');
            } else {
                $new_product = [
                    "pname"=>$params["pname"],
                    "uid"=>$params["uid"],
                    "zb_voice"=>$params["zb_voice"],
                    "fb_voice"=>$params["fb_voice"]
                ];
                $res = LiveProduct::create($new_product);
                $num = 0;

                foreach ($texts as $te) {
                    $item = [];
                    $item["pid"] = $res["id"];
                    $item["text"] = $te["text"];
                    $item["group"] = $te["group"];
                    $item["type"] = $te["type"];
                    LiveProductText::create($item);
                    $num = $num+1;

                }

            }
            // 提交事务
//            Db::commit();
//        }catch (Exception $e) {
//            // 回滚事务
//            Db::rollback();
//            return writeJson(200,false,'失败！');
//        }
        return writeJson(200, $num, '请求成功');

    }

    public function getTaskChild11(Request $request)
    {
        $params = $request->get();
        $info = LiveProductTaskChild::where("status", 11)->where("voice", $params["voice"])->findOrEmpty();

        if (!$info->isEmpty()) {
            $info->status = 12;
            $info->get_time = date("Y-m-d H:i:s");
            $info->save();
            return writeJson(200, $info, "成功");
        } else {
            return writeJson(200, [], '暂无');
        }
    }

    public function getProductText(Request $request)
    {
        $params = $request->get();
        $group = [];
        $info = LiveProductText::where("status", 1)->findOrEmpty();
        if (!$info->isEmpty()) {
            $group = LiveProductText::where("status", 1)->where("group", $info["group"])
                ->where("pid", $info["pid"])->select()->toArray();
            if (!empty($group)) {
                $ids = [];
                foreach ($group as $g) {
                    $ids[] = $g["id"];
                }
                LiveProductText::whereIn("id", $ids)->update([
                    "status"=>2,
                    "get_time"=>date("Y-m-d H:i:s")
                ]);
            }
        }
        return writeJson(200, $group, "成功");

    }

    public function backProductText(Request $request)
    {
        $params = $request->post();
        $ids = json_decode($params["ids"], true);
        LiveProductText::whereIn("id", $ids)->update([
            "status"=>3
        ]);
        return writeJson(200, true, "成功");

    }

    public function delTextByGroup(Request $request)
    {
        $params = $request->post();
//        由音频话术，拿到话术id
        $group = $params["group"];
        $tname = $params["tname"];
        $type = $params["type"];
        DB::startTrans();
        try {
            $task = LiveProductTask::where("tname", $tname)->findOrEmpty();
            if (!$task->isEmpty()) {
                $pid = $task["pid"];
                $tasks = LiveProductTask::where("pid")->select()->toArray();
    //            删除子任务
                foreach ($tasks as $s) {
                    LiveProductTaskChild::where("task_id", $s["id"])->where("group", $group)->where("type", $type)->delete();
                }
    //            删除话术表
                LiveProductText::where("pid", $pid)->where("group", $group)->where("type", $type)->delete();
            }
            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            return writeJson(20001, $e, '请求失败');
        }
        return writeJson(200, true, '请求成功');

    }

    public function consume(Request $request)
    {
        $params = $request->post();
        $count = 0;
        if(!empty($params['data'])){
            $items = $params['data'];
            foreach ($items as $item){
                $is_exists = LiveConsume::where('dy_id',$item['dy_id'])
                    ->where('date',$item['date'])
                    ->where('method',$item['method'])
                    ->where('plan_id',$item['plan_id'])
                    ->findOrEmpty();

                if($is_exists->isEmpty()){
                    LiveConsume::create($item);
                    $count++;
                }
            }

        }
        return writeJson(200, $count, '请求成功');
    }


    public function major(Request $request)
    {
        $params = $request->post();
        $count = 0;

        $contacts = LiveContact::select()->toArray();
        // 把关联关系做成映射键值对
        $key_values = [];
        foreach ($contacts as $contact){
            $key_values[$contact['douyhuid']] = $contact;
        }



        if(!empty($params['data'])){
            $items = $params['data'];
            foreach ($items as $item){
                if(isset($key_values[$item['douyhuid']])){
                    $item['zz'] = $key_values[$item['douyhuid']]['zz'];
                    $item['douyhmc'] = $key_values[$item['douyhuid']]['douyhmc'];
                    $item['remark'] = $key_values[$item['douyhuid']]['remark'];
                    $item['douyhid'] = $key_values[$item['douyhuid']]['douyhid'];
                    $item['type'] = $key_values[$item['douyhuid']]['type'];
                }



                $is_exists = LiveMajor::where('dingdid',$item['dingdid'])
                    ->findOrEmpty();

                if($is_exists->isEmpty()){
                    LiveMajor::create($item);
                    $count++;
                }else{
                    LiveMajor::where('dingdid',$item['dingdid'])->update($item);
                }
            }

        }
        return writeJson(200, $count, '请求成功');
    }



    public function contact(Request $request)
    {
        $params = $request->post();
        $count = 0;
        if(!empty($params['data'])){
            $items = $params['data'];
            foreach ($items as $item){
                // 判断组长和视频类型
                $item['zz'] = "";
                $item['type'] = "";
                if (strpos($item['remark'], ':') !== false) {
                    $result = explode(":", $item['remark']);
                    $item['zz'] = $result[0];
                    $item['type'] = $result[1];
                }

                if (strpos($item['remark'], '：') !== false) {
                    $result = explode("：", $item['remark']);
                    $item['zz'] = $result[0];
                    $item['type'] = $result[1];
                }


                $is_exists = LiveContact::where('douyhid',$item['douyhid'])
                    ->findOrEmpty();

                if($is_exists->isEmpty()){
                    LiveContact::create($item);
                    $count++;
                }else{

                    $is_exists->douyhmc = $item['douyhmc'];
                    $is_exists->douyhuid = $item['douyhuid'];
                    $is_exists->remark = $item['remark'];
                    $is_exists->zz = $item['zz'];
                    $is_exists->type = $item['type'];
                    $is_exists->save();
                }
            }

        }
        return writeJson(200, $count, '请求成功');
    }

    /*
     * 抖老板 账号数据保存
     * */
    public function commander(Request $request)
    {
        $params = $request->post();
        $count = 0;
        if(!empty($params['data'])){
            $items = $params['data'];
            foreach ($items as $item){
                $is_exists = LiveCommander::where('order_id',$item['order_id'])
                    ->findOrEmpty();

                if($is_exists->isEmpty()){
                    LiveCommander::create($item);
                    $count++;
                }
            }

        }
        return writeJson(200, $count, '请求成功');
    }



    public function returnZz($douyhmcbz)
    {
        $keys = ['钟总','大姑妈','小飞哥','福州测试','河南吕威','阿郑','范范','老朱','燕霞','億发','思伟','娜子'];
        foreach ($keys as $name){
            if (stripos($douyhmcbz, $name) !== false) {
                // 包含子串
                return $name;
            }
        }
    }

    public function count(Request $request)
    {
        $params = $request->get();

        $start_time = !empty($params['start_time'])? $params['start_time']:date('Y-m-d 00:00:00',time()-86400);
        $end_time = !empty($params['end_time'])? $params['end_time']:date('Y-m-d 23:59:59',time()-86400);

        $once = [];

        $list = LiveMajor::field(['id','douyhmc','chudqd','dingdzt','fukje','jingyj','douyhid','zz','type'])
            ->where('fuksj','>',$start_time)
            ->where('fuksj','<',$end_time)
            ->whereIn('yunyr',['俊伟','思伟','大姑妈','老朱','三毛','龙图阁','发总'
                ,'天宇工作室','天龙工作室','天福工作室','天美工作室','天珠工作室','天雄工作室','素萍工作室'])->select();
        foreach ($list as $item){
            // 判断最终订单类型
            $lastQd = (new LiveService())->lastQd($item['type'],$item['chudqd']);
            $item['lastQd'] = $lastQd;
            $once[] = $item;
        }


        // 开始二轮计算 轮询算汇总
        // 根据消耗 和 当日出单 做个并集 算出单日总计有多少组长出单 做成键值对的形式
        // 根据消耗算出当日组长
        // 算出时间段内的

        $start_day = !empty($params['start_time'])? date('Y-m-d',strtotime($params['start_time'])):date('Y-m-d',time()-86400);
        $end_day = !empty($params['end_time'])? date('Y-m-d',strtotime($params['end_time'])):date('Y-m-d',time()-86400);

        // 执行查询
        $result = LiveContact::alias('a')
            ->join('live_consume b', 'a.douyhid = b.dy_id', 'INNER')
            ->where('b.method', '推直播间')
            ->where('b.date','>=',$start_day)
            ->where('b.date','<=',$end_day)
            ->where('a.zz', '<>', '')
            ->field('a.zz, sum(b.consume) as total_consume')
            ->group('a.zz')
            ->select()->toArray();

        $formattedResult = [];
        foreach ($result as $item) {
            $item['total_jingyj'] = 0;
            $item['total_gmv'] = 0;

            $formattedResult[$item['zz']] = $item;

        }

        // 算出短视频消耗
        $video_consume = LiveConsume::field('sum(consume) as video_consume')
            ->where('method', '推商品')
            ->where('date','>=',$start_day)
            ->where('date','<=',$end_day)
            ->find();

        $formattedResult['短视频'] = [
            "total_jingyj" => 0,
            "total_gmv" => 0,
            "total_consume" =>  $video_consume['video_consume']
        ];


        foreach ($once as $on){
            $zzname = $on['zz'];
            // 判断类型
            if(!isset($formattedResult[$zzname])){
                $formattedResult[$zzname] = [
                    "total_jingyj" => 0,
                    "total_gmv" => 0,
                    "total_consume" => 0,
                    "zz" => $zzname
                ];
            }

            if($on['lastQd'] == "直播"){
                if($on['dingdzt'] != '订单退款/退货'){
                    $formattedResult[$zzname]['total_jingyj'] =  $formattedResult[$zzname]['total_jingyj'] + $on['jingyj'];

                }

                $formattedResult[$zzname]['total_gmv'] =  $formattedResult[$zzname]['total_gmv'] + $on['fukje'];


            }else{
                if($on['dingdzt'] != '订单退款/退货'){
                    $formattedResult['短视频']['total_jingyj'] =  $formattedResult['短视频']['total_jingyj'] + $on['jingyj'];
                }

                $formattedResult['短视频']['total_gmv'] =  $formattedResult['短视频']['total_gmv'] + $on['fukje'];

            }

        }

        return writeJson(200, $formattedResult, '请求成功');


    }
    public function countDy(Request $request)
    {
        $params = $request->get();

        $start_time = !empty($params['start_time'])? $params['start_time']:date('Y-m-d 00:00:00',time()-86400);
        $end_time = !empty($params['end_time'])? $params['end_time']:date('Y-m-d 23:59:59',time()-86400);

        $once = [];

        $list = LiveMajor::field(['id','douyhmc','chudqd','dingdzt','fukje','jingyj','douyhid','zz','type'])
            ->where('fuksj','>',$start_time)
            ->where('fuksj','<',$end_time)
            ->whereIn('yunyr',['俊伟','思伟','大姑妈','老朱','三毛','龙图阁','发总'
                ,'天宇工作室','天龙工作室','天福工作室','天美工作室','天珠工作室'])->select();
        foreach ($list as $item){
            // 判断最终订单类型
            $lastQd = (new LiveService())->lastQd($item['type'],$item['chudqd']);
            $item['lastQd'] = $lastQd;
            $once[] = $item;
        }


        // 开始二轮计算 轮询算汇总
        // 根据消耗 和 当日出单 做个并集 算出单日总计有多少组长出单 做成键值对的形式
        // 根据消耗算出当日组长
        // 算出时间段内的

        $start_day = !empty($params['start_time'])? date('Y-m-d',strtotime($params['start_time'])):date('Y-m-d',time()-86400);
        $end_day = !empty($params['end_time'])? date('Y-m-d',strtotime($params['end_time'])):date('Y-m-d',time()-86400);

        // 执行查询
        $result = LiveContact::alias('a')
            ->join('live_consume b', 'a.douyhid = b.dy_id', 'INNER')
            ->where('b.method', '推直播间')
            ->where('b.date','>=',$start_day)
            ->where('b.date','<=',$end_day)
            ->where('a.zz', '<>', '')
            ->field('a.zz,a.douyhid, sum(b.consume) as total_consume')
            ->group('a.zz,a.douyhid')
            ->select()->toArray();

        $formattedResult = [];
        foreach ($result as $item) {
            if (isset($formattedResult[$item['zz']])) {
                $formattedResult[$item['zz']]["total_consume"] = $formattedResult[$item['zz']]["total_consume"] + $item["total_consume"];
                $formattedResult[$item['zz']]["douyh"][] = $item["douyhid"];
            } else {
                $item['total_jingyj'] = 0;
                $item['total_gmv'] = 0;
                $item['total_livetime'] = 0;
                $item['douyh'] = array($item["douyhid"]);
                unset($item["douyhid"]);

                $formattedResult[$item['zz']] = $item;
            }
        }

        //直播场次查询
        $live_once = LiveSession::field("anchor_id, anchor_duration")
            ->where("anchor_start_time", ">=", $start_day)
            ->where('anchor_start_time','<',$end_day)
            ->where("platform", "抖音")->select();
        foreach ($live_once as $lon) {
            foreach ($formattedResult as $key=>$val) {
                if (in_array($lon["anchor_id"], $val["douyh"])) {
                    $formattedResult[$key]["total_livetime"] = $formattedResult[$key]["total_livetime"] + $lon["anchor_duration"];
                }
            }
        }

        // 算出短视频消耗
        $video_consume = LiveConsume::field('sum(consume) as video_consume')
            ->where('method', '推商品')
            ->where('date','>=',$start_day)
            ->where('date','<=',$end_day)
            ->find();

        $formattedResult['短视频'] = [
            "total_jingyj" => 0,
            "total_gmv" => 0,
            "total_consume" =>  $video_consume['video_consume']
        ];


        foreach ($once as $on){
            $zzname = $on['zz'];
            // 判断类型
            if(!isset($formattedResult[$zzname])){
                $formattedResult[$zzname] = [
                    "total_jingyj" => 0,
                    "total_gmv" => 0,
                    "total_consume" => 0,
                    "total_livetime" => 0,
                    "zz" => $zzname
                ];
            }

            if($on['lastQd'] == "直播"){
                if($on['dingdzt'] != '订单退款/退货'){
                    $formattedResult[$zzname]['total_jingyj'] =  $formattedResult[$zzname]['total_jingyj'] + $on['jingyj'];

                }

                $formattedResult[$zzname]['total_gmv'] =  $formattedResult[$zzname]['total_gmv'] + $on['fukje'];


            }else{
                if($on['dingdzt'] != '订单退款/退货'){
                    $formattedResult['短视频']['total_jingyj'] =  $formattedResult['短视频']['total_jingyj'] + $on['jingyj'];
                }

                $formattedResult['短视频']['total_gmv'] =  $formattedResult['短视频']['total_gmv'] + $on['fukje'];

            }

        }

        return writeJson(200, $formattedResult, '请求成功');


    }

    public function countTb(Request $request)
    {
        $params = $request->get();

        $start_time = !empty($params['start_time'])? $params['start_time']:date('Y-m-d 00:00:00',time()-86400);
        $end_time = !empty($params['end_time'])? $params['end_time']:date('Y-m-d 23:59:59',time()-86400);

        //订单查询
        $once = [];

        $list = LiveMajor::field(['id','douyhmc','chudqd','dingdzt','fukje','jingyj','douyhid','zz','type'])
            ->where('fuksj','>',$start_time)
            ->where('fuksj','<',$end_time)
            ->where("platform", "淘宝")->select();
        foreach ($list as $item){
            // 判断最终订单类型
            $lastQd = (new LiveService())->lastQd($item['type'],$item['chudqd']);
            $item['lastQd'] = $lastQd;
            $once[] = $item;
        }

        //直播场次查询
        $live_once = LiveSession::where("anchor_start_time", ">", $start_time)
            ->where('anchor_start_time','<',$end_time)
            ->where("platform", "淘宝")->select();


        // 执行查询
        $result = LiveContact::where('zz', '<>', '')
            ->where("platform", "淘宝")
            ->field('zz,douyhuid')
            ->group('zz,douyhuid')
            ->select()->toArray();

        $formattedResult = [];
        $zz_arr = [];
        foreach ($result as $item) {
            if (in_array($item["zz"], $zz_arr)) {
                $formattedResult[$item["zz"]]["douyh"][] = $item["douyhuid"];
            } else {
                $cell = [];
                $cell['zz'] = $item["zz"];
                $cell['total_jingyj'] = 0;
                $cell['total_gmv'] = 0;
                $cell['total_consume'] = 0;
                $cell['total_livetime'] = 0;
                $cell['douyh'] = [];
                $formattedResult[$item['zz']] = $cell;
                $zz_arr[] = $item['zz'];
            }
        }
        foreach ($formattedResult as $re) {
            $zzname = $re["zz"];
            foreach ($once as $on){
                if (in_array($on["douyhmc"], $re["douyh"])) {
                    if($on['dingdzt'] != '订单退款/退货'){
                        $formattedResult[$zzname]['total_jingyj'] =  $formattedResult[$zzname]['total_jingyj'] + $on['jingyj'];
                    }
                    $formattedResult[$zzname]['total_gmv'] =  $formattedResult[$zzname]['total_gmv'] + $on['fukje'];
                }
            }
            foreach ($live_once as $lon){
                if (in_array($lon["anchor_name"], $re["douyh"])) {
                    $formattedResult[$zzname]['total_livetime'] =  $formattedResult[$zzname]['total_livetime'] + intval($lon['anchor_duration']);
                }
            }
        }

        return writeJson(200, $formattedResult, '请求成功');


    }

    public function importmajor(Request $request){
        $file = $request->file('file');
        $event = new LiveMajor();

        $filename  = $file->getInfo()['tmp_name'];
        //设置excel格式
        $reader = PHPExcel_IOFactory::createReader('Excel2007');
        //载⼊excel⽂件
        $excel = $reader->load($filename);
        //读取第⼀张表
        $sheet = $excel->getSheet(0);
        //获取总⾏数
        $row_num = $sheet->getHighestRow();

        //获取总列数
        $col_num = 'P';
        $datas = []; //数组形式获取表格数据
        $head = [];
        $res = [];

        for($row=1;$row<=$row_num;$row++)
        {
            for($col='A';$col<=$col_num;$col++) {
                if ($row == 1) {
                    $head[] = $sheet->getCell($col."1")->getValue();
                } else {
                    $datas[$row-2][] = $sheet->getCell($col.$row)->getValue();
                }
            }
        }
        $array2 = ["shangpbt","shangpid","dianpmc","fuksj","dingdid","dingdzt","chudqd","fukje","ticb","yongj","douyhmc","douyhid","douyhuid","yunyr","platform","source"];
        if (array_diff_assoc($head, $array2) != NULL) {
            return writeJson(200,false,'表结构不正确！');
        }

        DB::startTrans();
        try {
            $save_data = [];
            $chongfu = 0;
            $num = 0;
            for ($row = 0; $row < count($datas); $row++) {
                $info = [];
                $add = [];
                $add["shangpbt"] = $datas[$row][0];
                $add["shangpid"] = trim($datas[$row][1]);
                $add["dianpmc"] = $datas[$row][2];
                $add["dingdid"] = str_replace(" ", "", trim($datas[$row][4]));
                $add["dingdzt"] = $datas[$row][5];
                $add["chudqd"] = $datas[$row][6];
                $add["fukje"] = $datas[$row][7];
                $add["ticb"] = $datas[$row][8];
                $add["yongj"] = $datas[$row][9];
                $add["douyhmc"] = $datas[$row][10];
                $add["douyhid"] = $datas[$row][11];
                $add["douyhuid"] = $datas[$row][12];
                $add["yunyr"] = $datas[$row][13];
                $add["platform"] = $datas[$row][14];
                $add["source"] = $datas[$row][15];
                $baseDate = 25569; // 1970年1月1日在Excel中的序列号
                // 转换为Unix时间戳（秒）
                $unixTimestamp = ($datas[$row][3] - $baseDate ) * 86400 -28858;
                // 格式化为日期时间字符串
                $add["fuksj"] = date('Y-m-d H:i:s', $unixTimestamp);

                if (!empty($add["dingdid"])) {
                    // 查重
                    $info = LiveMajor::where("dingdid", $add["dingdid"])->findOrEmpty();
                    if ($info->isEmpty()) {
//                        $save_data[] = $add;
                        $res = $event->create($add);
                        if ($res) {
                            $num++;
                        }
                    } else {
                        $chongfu++;
                    }
                } else {
//                    $save_data[] = $add;
                    $res = $event->create($add);
                    if ($res) {
                        $num++;
                    }
                }
            }
//            if (count($save_data) > 0) {
//                $res = $event->saveAll($save_data);
//            }
            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            return writeJson(200,$e->getMessage(),'导表失败！');
        }
        if ($num > 0) {
            return writeJson(200,$num,"完成！,重复{$chongfu}");
        } else {
            return writeJson(200,0,"失败了,重复{$chongfu}");

        }
    }

    public function insertMajor(Request $request)
    {
        $event = new LiveMajor();

        $params = $request->post();
        $data = json_decode($params["data"], true);
        $chongfu = 0;
        $num = 0;
        DB::startTrans();
        try {
            foreach ($data as $add) {
                if (!empty($add["dingdid"])) {
                    // 查重
                    $info = LiveMajor::where("dingdid", $add["dingdid"])->findOrEmpty();
                    if ($info->isEmpty()) {
                        if (strpos($add["fuksj"], "-") === false) {
                            $baseDate = 25569; // 1970年1月1日在Excel中的序列号
                            // 转换为Unix时间戳（秒）
                            $unixTimestamp = ($add["fuksj"] - $baseDate ) * 86400 -28858;
                            // 格式化为日期时间字符串
                            $add["fuksj"] = date('Y-m-d H:i:s', $unixTimestamp);
                        }
                        $res = $event->create($add);
                        if ($res) {
                            $num++;
                        }
                    } else {
                        $chongfu++;
                    }
                } else {
                    $res = $event->create($add);
                    if ($res) {
                        $num++;
                    }
                }
            }
            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            return writeJson(200,$e->getMessage(),'失败！');
        }
        return writeJson(200,true,"完成！新增{$num},重复{$chongfu}");

    }


    /*
     * 跟播计划入库
     * */
    public function genbo(Request $request)
    {
        // 检验当前计划是否有值
        $params = $request->post();
        $uid = LoginToken::getInstance()->getCurrentUid();
        $t = LiveGenbo::create([
            'task_name' => $params['task_name'],
            'txt' => $params['txt'],
            'uid' => $uid,
            'remark' => !empty($params['remark'])?$params['remark']:'',
            'qa' => $params['qa']
        ]);
        if($params['is_run'] == 1){
            (new LiveService())->genboTaskRun($t['id']);
        }

        return writeJson(200, $t, '添加成功');
    }


    /*
   * 跟播计划修改
   * */
    public function editGenbo(Request $request)
    {
        // 检验当前计划是否有值
        $params = $request->post();
        $uid = LoginToken::getInstance()->getCurrentUid();
        $t = LiveGenbo::where('id',$params['id'])->update([
            'task_name' => $params['task_name'],
            'txt' => $params['txt'],
            'uid' => $uid,
            'remark' => !empty($params['remark'])?$params['remark']:'',
            'qa' => $params['qa'],
            'is_run' => $params['is_run']
        ]);
        if($params['is_run'] == 1){
            (new LiveService())->genboTaskRun($params['id']);
        }

        return writeJson(200, $t, '修改成功');
    }

    public function delGenbo(Request $request)
    {
        $params = $request->post();
        $t = LiveGenbo::where('id',$params['id'])->delete();
        return writeJson(200, $t, '删除成功');
    }

    public function genboRun(Request $request)
    {
        $params = $request->post();
        $t = LiveGenbo::where('id',$params['id'])->update([
            'is_run' => $params['is_run']
        ]);
        if($params['is_run'] == 1){
            (new LiveService())->genboTaskRun($params['id']);
        }
        return writeJson(200, $t, '更改成功');
    }



    public function getGenboList(Request $request)
    {
        // 每个人看到自己的
        $params = $request->get();
        $uid = LoginToken::getInstance()->getCurrentUid();
        $genbo_query = new LiveGenbo();
        if($uid != 1){
            $genbo_query = $genbo_query->where('uid',$uid);
        }

        if(!empty($params['task_name'])){
            $genbo_query = $genbo_query->where('task_name',$params['task_name']);
        }

        if(!empty($params['remark'])){
            $genbo_query = $genbo_query->where('remark','like','%'.$params['remark'].'%');
        }

        $result = $genbo_query->paginate(20);
        return writeJson(200, $result, '跟播列表');

    }

    public function getGenboDetail(Request $request)
    {
        $params = $request->get();
        $genbo_query = new LiveGenbo();

        if(!empty($params['task_name'])){
            $genbo_query = $genbo_query->where('task_name',$params['task_name']);
        }


        $result = $genbo_query->where('is_run',1)->findOrEmpty();
        if($result->isEmpty()){
            return writeJson(200, null, '暂无计划');
        }
        
        return writeJson(200, $result, '跟播计划');
    }


    public function addContact(Request $request)
    {
        $params = $request->post();
        $count = 0;
        $is_exists = LiveContact::where('douyhid',$params['douyhid'])->findOrEmpty();

        if($is_exists->isEmpty()){
            LiveContact::create($params);
            $count++;
        } else {
            $is_exists->douyhid = $params["douyhid"];
            $is_exists->douyhmc = $params["douyhmc"];
            $is_exists->douyhuid = $params["douyhuid"];
            $is_exists->remark = $params["remark"];
            $is_exists->platform = $params["platform"];
            $is_exists->type = $params["type"];
            $is_exists->zz = $params["zz"];
            $count = $is_exists->save();
        }
        return writeJson(200, $count, '请求成功');
    }

    public function contactList(Request $request)
    {
        $params = $request->post();
        $pageSize = $params['pageSize'] ?? 50;

        $query = LiveContact::field("*");
        if (!empty($params["douyhid"])) {
            $query = $query->where("douyhid", $params["douyhid"]);
        }
        if (!empty($params["douyhmc"])) {
            $query = $query->where("douyhmc", $params["douyhmc"]);
        }
        if (!empty($params["douyhuid"])) {
            $query = $query->where("douyhuid", $params["douyhuid"]);
        }
        if (!empty($params["platform"])) {
            $query = $query->where("platform", $params["platform"]);
        }
        if (!empty($params["type"])) {
            $query = $query->where("type", $params["type"]);
        }
        if (!empty($params["zz"])) {
            $query = $query->where("zz", $params["zz"]);
        }
        if (!empty($params["remark"])) {
            $query = $query->whereLike("remark", $params["remark"]);
        }
        $list = $query->paginate($pageSize);
        return writeJson(200,$list,'数据列表！');

    }

    public function session(Request $request)
    {
        $params = $request->post();
        $count = 0;
        if(!empty($params['data'])){
            $items = $params['data'];
            foreach ($items as $item){
                $is_exists = LiveSession::where('anchor_cc_id',$item['anchor_cc_id'])->findOrEmpty();

                if($is_exists->isEmpty()){
                    $item["anchor_duration"] = str_replace(",", "", $item["anchor_duration"]);
                    LiveSession::create($item);
                    $count++;
                }
            }

        }
        return writeJson(200, $count, '请求成功');
    }

    /**
     * 淘宝账号直播效率报表
     * @param Request $request
     * @return \think\response\Json
     */
    public function countTbAccount(Request $request)
    {
        $params = $request->get();
        $start_time = !empty($params['start_time'])? $params['start_time']:date('Y-m-d 00:00:00',time()-86400);
        $end_time = !empty($params['end_time'])? $params['end_time']:date('Y-m-d 23:59:59',time()-86400);

        $result = [];
        //所有账号
        $result = LiveContact::where("platform", "淘宝")->select()->toArray();

        //直播时间
        $live_once = LiveSession::field("anchor_name,sum(anchor_duration) s")
            ->where("anchor_start_time", ">", $start_time)
            ->where('anchor_start_time','<',$end_time)
            ->where("platform", "淘宝")
            ->group("anchor_name")->select();
        foreach ($result as $key=>$val) {
            //初始化
            $result[$key]["consume"] = 0;
            $result[$key]["live_time"] = 0;
            $result[$key]["jingyj"] = 0;
            $result[$key]["profit"] = 0;
            $result[$key]["rate"] = 0;
            foreach ($live_once as $lon) {
                if ($val["douyhuid"] == $lon["anchor_name"]) {
                    $result[$key]["live_time"] = round($lon["s"]/60, 2);
                }
            }
        }
        //佣金
        $once = LiveMajor::field("douyhuid,sum(jingyj) s")
            ->where('fuksj','>',$start_time)
            ->where('fuksj','<',$end_time)
            ->where("platform", "淘宝")
            ->where("dingdzt", "<>", "订单退款/退货")
            ->group("douyhuid")->select();
        foreach ($result as $key=>$val) {
            foreach ($once as $on) {
                if ($val["douyhuid"] == $on["douyhuid"]) {
                    $result[$key]["jingyj"] = $on["s"];
                    $result[$key]["profit"] = $on["s"];
                }
            }
        }
        //效率
//        foreach ($result as $key=>$val) {
//            if ($val["live_time"] != 0) {
//                $result[$key]["rate"] = round(($val["jingyj"] - $val["consume"]) / $val["live_time"] * 1.38, 2);
//            } else {
//                $result[$key]["rate"] = 0;
//            }
//        }
        usort($result, function($a, $b) {
            return $b['profit'] <=> $a['profit']; // 使用太空船操作符进行倒序比较
        });
        return writeJson(200, $result, '请求成功');

    }

    /**
     * 抖音账号直播效率报表
     * @param Request $request
     * @return \think\response\Json
     */
    public function countDyLiveAccount(Request $request)
    {
        $params = $request->get();
        $start_time = !empty($params['start_time'])? $params['start_time']:date('Y-m-d 00:00:00',time()-86400);
        $end_time = !empty($params['end_time'])? $params['end_time']:date('Y-m-d 23:59:59',time()-86400);

        $result = [];
        //所有账号
        $result = LiveContact::where("platform", "抖音")
            ->whereIn("type", ["短直","直播"])->select()->toArray();

        //直播时间
        $live_once = LiveSession::field("anchor_id,sum(anchor_duration) s")
            ->where("anchor_start_time", ">", $start_time)
            ->where('anchor_start_time','<',$end_time)
            ->where("platform", "抖音")
            ->group("anchor_id")->select();
        foreach ($result as $key=>$val) {
            //初始化
            $result[$key]["consume"] = 0;
            $result[$key]["live_time"] = 0;
            $result[$key]["jingyj"] = 0;
            $result[$key]["profit"] = 0;
            $result[$key]["rate"] = 0;
            foreach ($live_once as $lon) {
                if ($val["douyhid"] == $lon["anchor_id"]) {
                    $result[$key]["live_time"] = round($lon["s"]/60, 2);
                }
            }
        }
        //佣金
        $once = LiveMajor::field("douyhid,sum(jingyj) s")
            ->where('fuksj','>',$start_time)
            ->where('fuksj','<',$end_time)
            ->where("platform", "抖音")
            ->where("chudqd", "直播")
            ->where("dingdzt", "<>", "订单退款/退货")
            ->group("douyhid")->select();
        foreach ($result as $key=>$val) {
            foreach ($once as $on) {
                if ($val["douyhid"] == $on["douyhid"]) {
                    $result[$key]["jingyj"] = $on["s"];
                }
            }
        }
        //消耗
        $start_day = !empty($params['start_time'])? date('Y-m-d',strtotime($params['start_time'])):date('Y-m-d',time()-86400);
        $end_day = !empty($params['end_time'])? date('Y-m-d',strtotime($params['end_time'])):date('Y-m-d',time()-86400);

        $consume_once = LiveConsume::field("dy_id,sum(consume) s")
            ->where('method', '推直播间')
            ->where('date','>=',$start_day)
            ->where('date','<=',$end_day)
            ->group("dy_id")->select();
        foreach ($result as $key=>$val) {
            foreach ($consume_once as $on) {
                if ($val["douyhid"] == $on["dy_id"]) {
                    $result[$key]["consume"] = $on["s"];
                }
            }
        }
        //效率
        foreach ($result as $key=>$val) {
            $result[$key]["profit"] = round($val["jingyj"] - $val["consume"], 2);
//            if ($val["live_time"] != 0) {
//                $result[$key]["rate"] = round(($val["jingyj"] - $val["consume"]) / $val["live_time"] * 1.38, 2);
//            } else {
//                $result[$key]["rate"] = 0;
//            }
        }
        usort($result, function($a, $b) {
            return $b['profit'] <=> $a['profit']; // 使用太空船操作符进行倒序比较
        });
        return writeJson(200, $result, '请求成功');

    }

    /**
     * 抖音短视频账号效率报表
     */
    public function countDyVideoAccount(Request $request)
    {
        $params = $request->get();
        $start_time = !empty($params['start_time'])? $params['start_time']:date('Y-m-d 00:00:00',time()-86400);
        $end_time = !empty($params['end_time'])? $params['end_time']:date('Y-m-d 23:59:59',time()-86400);

        $result = [];
        //所有账号
        $result = LiveContact::where("platform", "抖音")
            ->where("type", "<>", "")->select()->toArray();
        foreach ($result as $key=>$val) {
            //初始化
            $result[$key]["consume"] = 0;
            $result[$key]["live_time"] = 0;
            $result[$key]["jingyj"] = 0;
            $result[$key]["profit"] = 0;
            $result[$key]["rate"] = 0;
        }
        //佣金
        $once = LiveMajor::field("douyhuid,sum(jingyj) s")
            ->where('fuksj','>',$start_time)
            ->where('fuksj','<',$end_time)
            ->where("platform", "抖音")
            ->where("chudqd", "视频")
            ->where("dingdzt", "<>", "订单退款/退货")
            ->group("douyhuid")->select();
        foreach ($result as $key=>$val) {
            foreach ($once as $on) {
                if ($val["douyhuid"] == $on["douyhuid"]) {
                    $result[$key]["jingyj"] = $on["s"];
                }
            }
        }
        //消耗
        $start_day = !empty($params['start_time'])? date('Y-m-d',strtotime($params['start_time'])):date('Y-m-d',time()-86400);
        $end_day = !empty($params['end_time'])? date('Y-m-d',strtotime($params['end_time'])):date('Y-m-d',time()-86400);

        $consume_once = LiveConsume::field("dy_id,sum(consume) s")
            ->where('method', '推商品')
            ->where('date','>=',$start_day)
            ->where('date','<=',$end_day)
            ->group("dy_id")->select();
        foreach ($result as $key=>$val) {
            foreach ($consume_once as $on) {
                if ($val["douyhid"] == $on["dy_id"]) {
                    $result[$key]["consume"] = $on["s"];
                }
            }
        }
        //利润
        foreach ($result as $key=>$val) {
            $result[$key]["profit"] = round($val["jingyj"] - $val["consume"], 2);
        }
        usort($result, function($a, $b) {
            return $b['profit'] <=> $a['profit']; // 使用太空船操作符进行倒序比较
        });
        return writeJson(200, $result, '请求成功');

    }

//    -----------------------------------------直播3.0---------------------------------------

    /**
     * @param Request $group_name
     * @param Request $ks_id
     * @param Request $ks_name
     * @return \think\response\Json
     */
    public function addGroup(Request $request)
    {
        $params = $request->post();
        if (isset($params["uid"]) && !empty($params["uid"])) {
            $uid = $params["uid"];
        } else {
            $uid = LoginToken::getInstance()->getCurrentUid();
        }
        $params["uid"] = $uid;

        if (empty($params["id"])) {
            $res = LiveMother::create($params);
        } else {
            $res = LiveMother::where("id", $params["id"])->update($params);
            //todo 更新缓存
            //检查计划里有没有这个mid
            $plans = Cache::store('redis')->get('live3_plans');
            if (isset($plans[$params['id']])) {
                $plans[$params['id']]['group_name'] = $params["group_name"];
                $plans[$params['id']]['ks_id'] = $params["ks_id"];
                $plans[$params['id']]['ks_name'] = $params["ks_name"];
                $plans[$params['id']]['is_douyin'] = $params["is_douyin"];
                $plans[$params['id']]['text'] = $params["text"];
                $plans[$params['id']]['qa'] = $params["qa"];
                Cache::store('redis')->set('live3_plans', $plans);
            }
        }


        return writeJson(200, $res, '请求成功');
    }

    public function delGroup(Request $request)
    {
        $params = $request->get();
        $uid = LoginToken::getInstance()->getCurrentUid();
        $params["uid"] = $uid;

        if (!empty($params["id"])) {
            //检查计划里有没有这个mid
            $plans = Cache::store('redis')->get('live3_plans');
            if (isset($plans[$params['id']])) {
                unset($plans[$params['id']]);
                Cache::store('redis')->set('live3_plans', $plans);
            }
            //删子
            LiveChild::where("m_id", $params["id"])->delete();
            //删母
            $res = LiveMother::where("id", $params["id"])->delete();
        }

        return writeJson(200, $res, '请求成功');
    }

    public function groupList(Request $request)
    {
        $params = $request->get();

        $uid = LoginToken::getInstance()->getCurrentUid();
        $query = LiveMother::field("*");

        if (!empty($params["group_name"])) {
            $query = $query->where("group_name", $params["group_name"]);
        }
        if (!empty($params["ks_id"])) {
            $query = $query->where("ks_id", $params["ks_id"]);
        }
        if (!empty($params["ks_name"])) {
            $query = $query->where("ks_name", $params["ks_name"]);
        }
        if (!empty($params["uid"])) {
            $query = $query->where("uid", $params["uid"]);
        }
        if ($uid != 1) {
            $query = $query->where("uid", $uid);
        }
        $list = $query->select()->toArray();

        $ids = [];
        foreach ($list as $key=>$li) {
            $list[$key]["childs"] = [];
            $ids[] = $li["id"];
        }
        $childs = LiveChild::whereIn("m_id", $ids)->select()->toArray();
        foreach ($list as $key=>$li) {
            foreach ($childs as $c) {
                if ($li["id"] == $c["m_id"]) {
                    $list[$key]["childs"][] = $c;
                }
            }
        }

        return writeJson(200, $list, '请求成功');
    }

    public function addChild(Request $request)
    {
        $params = $request->post();
        if (empty($params["id"])) {
            $res = LiveChild::create($params);
        } else {
            $res = LiveChild::where("id", $params["id"])->update($params);
        }
        //todo 更新缓存
        //检查计划里有没有这个mid
        $plans = Cache::store('redis')->get('live3_plans');
        if (isset($plans[$params['m_id']])) {
            //查最新child信息
            $child_info = LiveChild::where("m_id", $params['m_id'])->select()->toArray();
            $plans[$params['m_id']]['menu'] = $child_info;
            Cache::store('redis')->set('live3_plans', $plans);
        }
        return writeJson(200, $res, '请求成功');
    }

    public function delChild(Request $request)
    {
        $params = $request->get();
        if (!empty($params["id"])) {
            $res = LiveChild::where("id", $params["id"])->delete();
        }
        //todo 更新缓存
        //检查计划里有没有这个mid
        $plans = Cache::store('redis')->get('live3_plans');
        if (isset($plans[$params['m_id']])) {
            //查最新child信息
            $child_info = LiveChild::where("m_id", $params['m_id'])->select()->toArray();
            $plans[$params['m_id']]['menu'] = $child_info;
            Cache::store('redis')->set('live3_plans', $plans);
        }
        return writeJson(200, $res, '请求成功');
    }

    public function childList(Request $request)
    {
        $params = $request->get();
        $list = LiveChild::where("m_id", $params["m_id"])->select()->toArray();
        return writeJson(200, $list, '请求成功');
    }


    public function test()
    {
//        Cache::store('redis')->rm('live3_plans');
        // 使用Redis驱动
//        Cache::store('redis')->set('live3_plans', 'value', 3600);
        $value = Cache::store('redis')->get('live3_plans');
        unset($value['25']);
        Cache::store('redis')->set('live3_plans', $value);


        if (!$value) {
            return writeJson(200, false, '未创建计划');
        } else {
            return writeJson(200, $value, '请求成功');
        }
    }

    /**
     * 新增计划
     */
    public function addPlan(Request $request)
    {
        $params = $request->post();
        $m_id = $params["m_id"];
        $tlm= $params["tlm"];
        $m_live= $params["m_live"];
        $data = $params["childs_live"];
//        $data = json_decode($params["childs_live"], true);

        $m_info = LiveMother::where("id", $m_id)->findOrEmpty();
        $child_info = LiveChild::where("m_id", $m_id)->select()->toArray();
        foreach ($child_info as $key=>$val) {
            foreach ($data as $d) {
                if ($val["id"] == $d["id"]) {
                    $child_info[$key]["dy_link"] = $d["dy_link"]??null;
                    $child_info[$key]["tb_link"] = $d["tb_link"]??null;
                    $child_info[$key]["jd_link"] = $d["jd_link"]??null;
                }
            }
        }

        $plans = Cache::store('redis')->get('live3_plans');
        //检查当前mid是否已有计划
        if (isset($plans[$m_id])) {
            unset($plans[$m_id]);
        }

        $plans[$m_id] = array(
            "m_id"=>$m_id,
            "m_live"=>$m_live,
            "group_name"=>$m_info["group_name"],
            "ks_id"=>$m_info["ks_id"],
            "ks_name"=>$m_info["ks_name"],
            "is_douyin"=>$m_info["is_douyin"],
            "text"=>$m_info["text"],
            "qa"=>$m_info["qa"],
            "uid"=>$m_info["uid"],
            "tlm"=>$tlm,
            "c_child_id"=>"",
            "menu"=>$child_info
        );
        Cache::store('redis')->set('live3_plans', $plans);

        return writeJson(200, true, '请求成功');
    }

    public function delPlan(Request $request)
    {
        $params = $request->get();
        $plans = Cache::store('redis')->get('live3_plans');
        unset($plans[$params['m_id']]);
        Cache::store('redis')->set('live3_plans', $plans);
        return writeJson(200, true, '请求成功');
    }

    public function planCache(Request $request)
    {
        $params = $request->get();
        $uid = LoginToken::getInstance()->getCurrentUid();
        $result = [];

        $plans = Cache::store('redis')->get('live3_plans');
        if (!$plans) {
            return writeJson(200, false, '未创建计划');
        }
        //遍历查找当前账号下的计划
        foreach ($plans as $plan) {
            if ($uid == 1) {
                $result[] = $plan;
            } else {
                if ($plan["uid"] == $uid) {
                    $result[] = $plan;
                }
            }
        }
        return writeJson(200, $result, '请求成功');
    }

    public function chooseChild(Request $request)
    {
        $params = $request->get();
        $plans = Cache::store('redis')->get('live3_plans');
        //匹配当前mid cid
        if (isset($plans[$params["m_id"]])) {
            $plans[$params["m_id"]]["c_child_id"] = $params["c_id"];
            Cache::store('redis')->set('live3_plans', $plans);
        } else {
            return writeJson(200, false, '计划不存在');
        }

        return writeJson(200, true, '请求成功');
    }

    public function getChildStatus(Request $request)
    {
        $params = $request->get();
        $result = array("is_on"=>0, "tlm"=>"", "main_pic"=>"", "audio_url"=>"");
        $plans = Cache::store('redis')->get('live3_plans');

        if (!isset($plans[$params["m_id"]])) {
            return writeJson(200, [], '计划不存在');
        }
        $c_child_id = $plans[$params["m_id"]]["c_child_id"];
        if ($c_child_id == $params["c_id"]) {
            $result["is_on"] = 1;
            $result["tlm"] = $plans[$params["m_id"]]["tlm"];
        }

        //如果是淘宝直播间 传图片
        $menu = $plans[$params["m_id"]]["menu"];
        foreach ($menu as $m) {
            if ($m["id"] == $params["c_id"]) {
                //获取5分钟内最新的记录
                $info = TbLog::where("app_id", $m["tb_id"])->order("id desc")->findOrEmpty();
                if (!$info->isEmpty()) {
                    //返回商品图
                    $result["main_pic"] = $info["img"];

                    $five_min_ago_ts = strtotime(date("Y-m-d H:i:s", time() - 300));
                    $create_time_ts = strtotime($info["create_time"]);
                    if ($create_time_ts > $five_min_ago_ts) {
                        //创建时间在5分钟内
                        $list = TbAudio::where("pid", $info["pid"])->orderRand()->findOrEmpty();
                    }
                }
                if (empty($list)) {
                    $list = TbAudio::where("pid", "common")->orderRand()->findOrEmpty();
                }
                $result["audio_url"] = $list["audio"];
            }
        }


        return writeJson(200, $result, '请求成功');

    }
}